/*
 * File      : drv_uart.c
 * This file is part of RT-Thread RTOS
 * COPYRIGHT (C) 2008 - 2016, RT-Thread Development Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Change Logs:
 * Date           Author       Notes
 * 2015-11-19     Urey         the first version
 */
#include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>

#include <string.h>

#include "board.h"
#include "drv_uart.h"
#include "drv_gpio.h"
#include "drv_clock.h"
 
struct jz_uart_s
{
    rt_uint32_t hw_base;

    rt_uint32_t irqno;
    char name[RT_NAME_MAX];
};

static rt_err_t uart_configure          (struct rt_serial_device *serial, struct serial_configure *cfg);
static rt_err_t uart_control            (struct rt_serial_device *serial, int cmd, void *arg);
static int      uart_putc               (struct rt_serial_device *serial, char c);
static int      uart_getc               (struct rt_serial_device *serial);
static rt_size_t uart_dma_transmit      (struct rt_serial_device *serial, rt_uint8_t *buf, rt_size_t size, int direction);

static void     uart_irq_handler        (int irqno, void *param);

const struct rt_uart_ops _uart_ops =
{
    uart_configure,
    uart_control,
    uart_putc,
    uart_getc,
    uart_dma_transmit
};

struct baudtoregs_t
{
    unsigned int baud;
    unsigned short div;
    unsigned int umr:5;
    unsigned int uacr:12;
};

static struct baudtoregs_t baudtoregs[] = 
{
    /*
      The data is generated by a python,
      the script is tools/tty/get_divisor.py
     */
 #if (BOARD_EXTAL_CLK == 24000000)
    {50,0x7530,0x10,0x0},
    {75,0x4e20,0x10,0x0},
    {110,0x3521,0x10,0x0},
    {134,0x2b9d,0x10,0x0},
    {150,0x2710,0x10,0x0},
    {200,0x1d4c,0x10,0x0},
    {300,0x1388,0x10,0x0},
    {600,0x9c4,0x10,0x0},
    {1200,0x4e2,0x10,0x0},
    {1800,0x340,0x10,0x0},
    {2400,0x271,0x10,0x0},
    {4800,0x138,0x10,0x0},
    {9600,0x9c,0x10,0x0},
    {19200,0x4e,0x10,0x0},
    {38400,0x27,0x10,0x0},
    {57600,0x1a,0x10,0x0},
    {115200,0xd,0x10,0x0},
    {230400,0x6,0x11,0x550},
    {460800,0x3,0x11,0x550},
    {500000,0x3,0x10,0x0},
    {576000,0x3,0xd,0x0},
    {921600,0x2,0xd,0x0},
    {1000000,0x2,0xc,0x0},
    {1152000,0x1,0x14,0x400},
    {1500000,0x1,0x10,0x0},
    {2000000,0x1,0xc,0x0},
    {2500000,0x1,0x9,0x780},
    {3000000,0x1,0x8,0x0},
    {3500000,0x1,0x6,0x400},
    {4000000,0x1,0x6,0x0},
#elif (BOARD_EXTAL_CLK == 26000000)
    {50,0x7ef4,0x10,0x0},
    {75,0x546b,0x10,0x0},
    {110,0x398f,0x10,0x0},
    {134,0x2f40,0x10,0x0},
    {150,0x2a36,0x10,0x0},
    {200,0x1fbd,0x10,0x0},
    {300,0x151b,0x10,0x0},
    {600,0xa8e,0x10,0x0},
    {1200,0x547,0x10,0x0},
    {1800,0x385,0x10,0x0},
    {2400,0x2a4,0x10,0x0},
    {4800,0x152,0x10,0x0},
    {9600,0xa9,0x10,0x0},
    {19200,0x54,0x10,0x2},
    {38400,0x2a,0x10,0x2},
    {57600,0x1c,0x10,0x2},
    {115200,0xe,0x10,0x2},
    {230400,0x7,0x10,0x2},
    {460800,0x4,0xe,0x2},
    {500000,0x3,0x11,0x550},
    {576000,0x3,0xf,0x2},
    {921600,0x2,0xe,0x2},
    {1000000,0x2,0xd,0x0},
    {1152000,0x2,0xb,0x248},
    {1500000,0x1,0x11,0x550},
    {2000000,0x1,0xd,0x0},
    {2500000,0x1,0xa,0x2a0},
    {3000000,0x1,0x8,0x700},
    {3500000,0x1,0x7,0x2a0},
    {4000000,0x1,0x6,0x7c0},
#elif (BOARD_EXTAL_CLK == 48000000)
    {50,0xea60,0x10,0x0},
    {75,0x9c40,0x10,0x0},
    {110,0x6a42,0x10,0x0},
    {134,0x573a,0x10,0x0},
    {150,0x4e20,0x10,0x0},
    {200,0x3a98,0x10,0x0},
    {300,0x2710,0x10,0x0},
    {600,0x1388,0x10,0x0},
    {1200,0x9c4,0x10,0x0},
    {1800,0x67f,0x10,0x0},
    {2400,0x4e2,0x10,0x0},
    {4800,0x271,0x10,0x0},
    {9600,0x138,0x10,0x0},
    {19200,0x9c,0x10,0x0},
    {38400,0x4e,0x10,0x0},
    {57600,0x34,0x10,0x0},
    {115200,0x1a,0x10,0x0},
    {230400,0xd,0x10,0x0},
    {460800,0x6,0x11,0x550},
    {500000,0x6,0x10,0x0},
    {576000,0x5,0x10,0x700},
    {921600,0x3,0x11,0x550},
    {1000000,0x3,0x10,0x0},
    {1152000,0x3,0xd,0x0},
    {1500000,0x2,0x10,0x0},
    {2000000,0x2,0xc,0x0},
    {2500000,0x1,0x13,0x84},
    {3000000,0x1,0x10,0x0},
    {3500000,0x1,0xd,0x600},
    {4000000,0x1,0xc,0x0},
#endif
};
static unsigned short quot1[3] = {0}; /* quot[0]:baud_div, quot[1]:umr, quot[2]:uacr */

static unsigned short *get_divisor(unsigned int baud)
{
    struct baudtoregs_t *bt;
    int index;

    for (index = 0; index < sizeof(baudtoregs)/sizeof(baudtoregs[0]); index ++)
    {
        bt = &baudtoregs[index];
        if (bt->baud == baud)
        {
            break;
        }
    }

    if (index < sizeof(baudtoregs)/sizeof(baudtoregs[0])) 
    {
        quot1[0] = bt->div;
        quot1[1] = bt->umr;
        quot1[2] = bt->uacr;
        return quot1;
    }

    return NULL;
}

/*
 * UART Initiation
 */
void rt_hw_uart_init(void)
{
    struct rt_serial_device *serial;
    struct jz_uart_s        *uart;
    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;

#ifdef RT_USING_UART0 /* for BT */
    {
        static struct rt_serial_device  serial0;
        static struct jz_uart_s         uart0;

        serial  = &serial0;
        uart    = &uart0;

        serial->ops              = &_uart_ops;
        serial->config           = config;
        serial->config.bufsz     = 2048;
        serial->config.baud_rate = 115200;

        uart->hw_base   = UART0_BASE;
        uart->irqno     = IRQ_UART0;
        strcpy(uart->name, "uart0");

        /* PC10/11/12/13 as RXD/TXD/RTS/CTS */
        gpio_set_func(GPIO_PORT_C, GPIO_Pin_10, GPIO_FUNC_0);
        gpio_set_func(GPIO_PORT_C, GPIO_Pin_11, GPIO_FUNC_0);
        gpio_set_func(GPIO_PORT_C, GPIO_Pin_12, GPIO_FUNC_0);
        gpio_set_func(GPIO_PORT_C, GPIO_Pin_13, GPIO_FUNC_0);

        clk_enable(clk_get("uart0"));
        {
            extern int uart0_clk(void);

            uart0_clk();
        }

        rt_hw_serial_register(serial,
                              "uart0",
                              RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                              uart);
    }
#endif

#ifdef RT_USING_UART1
    {
        static struct rt_serial_device  serial1;
        static struct jz_uart_s         uart1;

        serial  = &serial1;
        uart    = &uart1;
        strcpy(uart->name, "uart1");

        serial->ops              = &_uart_ops;
        serial->config           = config;
        serial->config.baud_rate = 115200;

        uart->hw_base   = UART1_BASE;
        uart->irqno     = IRQ_UART1;

        /* PD2/3/4/5 as RXD/TXD/RTS/CTS */
        gpio_set_func(GPIO_PORT_D, GPIO_Pin_2, GPIO_FUNC_1);
        gpio_set_func(GPIO_PORT_D, GPIO_Pin_3, GPIO_FUNC_1);
        gpio_set_func(GPIO_PORT_D, GPIO_Pin_4, GPIO_FUNC_1);
        gpio_set_func(GPIO_PORT_D, GPIO_Pin_5, GPIO_FUNC_1);

        clk_enable(clk_get("uart1"));
        {
            extern int uart1_clk(void);

            uart1_clk();
        }

        rt_hw_serial_register(serial,
                              "uart1",
                              RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                              uart);
    }
#endif

#ifdef RT_USING_UART2
    {
        static struct rt_serial_device  serial2;
        static struct jz_uart_s         uart2;

        serial  = &serial2;
        uart    = &uart2;
        strcpy(uart->name, "uart2");

#ifdef CONFIG_SYS_UART2_PD
        gpio_set_func(GPIO_PORT_C,GPIO_Pin_31,GPIO_INPUT | GPIO_PULL);
        gpio_set_func(GPIO_PORT_D,GPIO_Pin_4,GPIO_FUNC_0);
        gpio_set_func(GPIO_PORT_D,GPIO_Pin_5,GPIO_FUNC_0);
#else
        //USE JTAG IO for UART2
        gpio_set_func(GPIO_PORT_D,GPIO_Pin_4,GPIO_INPUT | GPIO_PULL);
        gpio_set_func(GPIO_PORT_D,GPIO_Pin_5,GPIO_INPUT | GPIO_PULL);
        gpio_set_func(GPIO_PORT_C,GPIO_Pin_31,GPIO_FUNC_1 | GPIO_PULL);
#endif

        serial->ops              = &_uart_ops;
        serial->config           = config;
        serial->config.baud_rate = 115200;

        uart->hw_base   = UART2_BASE;
        uart->irqno     = IRQ_UART2;

        clk_enable(clk_get("uart2"));

        rt_hw_serial_register(serial,
                              "uart2",
                              RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
                              uart);
    }
#endif
}

/*
 * UART interface
 */
static rt_err_t uart_configure (struct rt_serial_device *serial, struct serial_configure *cfg)
{
    rt_uint32_t baud_div;
    unsigned short *quot1; 
    struct jz_uart_s * uart;

    RT_ASSERT(serial != RT_NULL);
    serial->config = *cfg;

    uart = serial->parent.user_data;
    RT_ASSERT(uart != RT_NULL);

    /* Init UART Hardware */
    UART_IER(uart->hw_base) = 0; /* clear interrupt */
    UART_FCR(uart->hw_base) = ~UARTFCR_UUE; /* disable UART unite */

    /* Enable UART clock */

    /* Set both receiver and transmitter in UART mode (not SIR) */
    UART_SIRCR(uart->hw_base) = ~(SIRCR_RSIRE | SIRCR_TSIRE);

    /* Set databits, stopbits and parity. (8-bit data, 1 stopbit, no parity) */
    UART_LCR(uart->hw_base) = UARTLCR_WLEN_8;

    /* set baudrate */
    quot1 = get_divisor(cfg->baud_rate);
    if (quot1 == RT_NULL)
    {
#if defined(RT_USING_JZ4750) || defined(RT_USING_JZ4755) || defined(RT_USING_JZ4760)
        if(REG_CPM_CPCCR & (1UL << 30))
        {
            /* CPCCR.ECS = 1: clock source is EXCLK/2 */
            baud_div = BOARD_EXTAL_CLK / 2 / 16 / cfg->baud_rate;
        }
        else
#endif
        {
             /* CPCCR.ECS = 0: clock source is EXCLK */
             baud_div = BOARD_EXTAL_CLK / 16 / cfg->baud_rate;
        }

        UART_DLHR(uart->hw_base) = (baud_div >> 8) & 0xff;
        UART_DLLR(uart->hw_base) = baud_div & 0xff;
        UART_LCR(uart->hw_base) &= ~UARTLCR_DLAB;
    }
    else
    {       
        UART_LCR(uart->hw_base) |= UARTLCR_DLAB;
        UART_DLHR(uart->hw_base) = (quot1[0] >> 8) & 0xff;
        UART_DLLR(uart->hw_base) = quot1[0] & 0xff;
        UART_LCR(uart->hw_base) &= ~UARTLCR_DLAB;

        UART_UMR(uart->hw_base)  = quot1[1] & 0xff;
        UART_UACR(uart->hw_base) = quot1[2] & 0xff;
    }

    if (uart->hw_base == UART0_BASE)
    {
        rt_kprintf("enable uart0 CTS/RTS and hw flow control\n");
        rt_kprintf("baudrate => %d\n", cfg->baud_rate);

        rt_kprintf("div: %d, umr %d, uacr %d\n", quot1[0], quot1[1], quot1[2]);

        /* configure CTS/RTS and hardware flow control */
        UART_MCR(uart->hw_base) |= (UARTMCR_MCE | UARTMCR_FCM);
    }
    else if (uart->hw_base == UART1_BASE)
    {
        rt_kprintf("enable uart1 CTS/RTS and hw flow control\n");
        rt_kprintf("baudrate => %d\n", cfg->baud_rate);

        rt_kprintf("div: %d, umr %d, uacr %d\n", quot1[0], quot1[1], quot1[2]);

        /* configure CTS/RTS and hardware flow control */
        UART_MCR(uart->hw_base) |= (UARTMCR_MCE | UARTMCR_FCM);
    }

    /* Enable UART unit, enable and clear FIFO */
    UART_FCR(uart->hw_base) = UARTFCR_UUE | UARTFCR_FE | UARTFCR_TFLS | UARTFCR_RFLS;

    return (RT_EOK);
}

int uart_set_baudrate(int baudrate)
{
    unsigned short *quot1;
    struct jz_uart_s * uart;
    struct rt_serial_device *serial;

    serial = (struct rt_serial_device *)rt_device_find("uart0");
    uart = serial->parent.user_data;
    RT_ASSERT(uart != RT_NULL);

    /* set baudrate */
    quot1 = get_divisor(baudrate);
    if (quot1)
    {
        UART_LCR(uart->hw_base) |= UARTLCR_DLAB;
        UART_DLHR(uart->hw_base) = (quot1[0] >> 8) & 0xff;
        UART_DLLR(uart->hw_base) = quot1[0] & 0xff;
        UART_LCR(uart->hw_base) &= ~UARTLCR_DLAB;

        UART_UMR(uart->hw_base)  = quot1[1] & 0xff;
        UART_UACR(uart->hw_base) = quot1[2] & 0xff;
    }

    rt_kprintf("change baudrate done!\n");
    return 0;
}

static rt_err_t uart_control (struct rt_serial_device *serial, int cmd, void *arg)
{
    struct jz_uart_s * uart;

    uart = serial->parent.user_data;

    RT_ASSERT(uart != RT_NULL);

    switch (cmd)
    {
    case RT_DEVICE_CTRL_CLR_INT:
        /* Disable the UART Interrupt */
        UART_IER(uart->hw_base) &= ~(UARTIER_RIE | UARTIER_RTIE);
        rt_hw_interrupt_mask(uart->irqno);
        break;

    case RT_DEVICE_CTRL_SET_INT:
        /* install interrupt */
        rt_hw_interrupt_install(uart->irqno, uart_irq_handler,
                                serial, uart->name);
        rt_hw_interrupt_umask(uart->irqno);

        /* Enable the UART Interrupt */
        UART_IER(uart->hw_base) |= (UARTIER_RIE | UARTIER_RTIE);
        break;
    }

    return (RT_EOK);
}

static int uart_putc (struct rt_serial_device *serial, char c)
{
    struct jz_uart_s* uart;
    int i = 0;

    uart = serial->parent.user_data;

    /* FIFO status, contain valid data */
    while (!((UART_LSR(uart->hw_base) & (UARTLSR_TDRQ | UARTLSR_TEMT)) == 0x60))
    {
        i ++;
        if (i > 0xfffff)
        {
            rt_kprintf("uart lst=>0x%02x\n", UART_LSR(uart->hw_base));
            i = 0;
        }
    }
    /* write data */
    UART_TDR(uart->hw_base) = c;

    return (1);
}

static int uart_getc (struct rt_serial_device *serial)
{
    struct jz_uart_s* uart = serial->parent.user_data;

    /* Receive Data Available */
    if (UART_LSR(uart->hw_base) & UARTLSR_DR)
    {
        return UART_RDR(uart->hw_base);
    }

    return (-1);
}

static rt_size_t uart_dma_transmit (struct rt_serial_device *serial, rt_uint8_t *buf, rt_size_t size, int direction)
{
    return (0);
}

/* UART interrupt handler */
static void uart_irq_handler(int irqno, void *param)
{
    rt_ubase_t isr;
    struct rt_serial_device *serial = (struct rt_serial_device*)param;
    struct jz_uart_s* uart = serial->parent.user_data;

    /* read interrupt status and clear it */
    isr = UART_ISR(uart->hw_base);
    if (isr & UARTISR_IID_RDI)      /* Receive Data Available */
    {
        rt_hw_serial_isr(serial,RT_SERIAL_EVENT_RX_IND);
    }

    if(isr & UARTISR_IID_THRI)
    {
        rt_hw_serial_isr(serial,RT_SERIAL_EVENT_TX_DONE);
    }
}
